<?php

function ext_search($text,$needle){
	return preg_match_all('/'.str_replace(array('[',']','*','?','.','(',')','\\','/','+'), array('\[','\]','\*','\?','\.','\(','\)','\\\\','\/','\+'), $needle).'/i', strip_tags($text), $matches);
}

function rus_strtolower($str){ # Костыль, пока php не научится работать с кириллицей
	$big=array('А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П','Р','С','Т','У','Ф','Х','Ц','Ч','Ш','Щ','Ъ','Ы','Ь','Э','Ю','Я');
	$sml=array('а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ы','ь','э','ю','я');
	return strtolower(str_replace($big,$sml,$str));
}

function ext_search_hl ($str,$hl) { # Обрезает абзац и подсвечивает найденное
	$str=rus_strtolower(strip_tags($str));
	$pos=strpos($str,$hl);
	return hook(str_replace($hl,'<strong style="color:red">'.$hl.'</strong>',($pos?'...':'').preg_replace('/\s([^\s]*)$/i','...',substr($str,($pos<100?0:$pos-100),250))));
}

echo '<h2><a href="'.generate_link('ext=search').'">'.$_l['ext_search']['search'].'</a></h2>';
searchform(clean_str(@$_v['q']));

if(isset($_v['whatdoreplace'])||$_v['q']) { # Если есть строка поиска
	$_v['whatdoreplace']=$_v['q'];
	$needle=clean_str($_v['whatdoreplace']);
	echo '<h2><a href="'.generate_link('ext=search&q='.$needle).'">'.$_l['ext_search']['results'].'</a></h2>';
	
	# Начинаем поиск по блогу
	$posts=getapts();
	
	foreach ($posts as $p){
		if(!gbuffer($p,'close')||ADMIN){
			$post=post_info($p);
			$n=ext_search($post['text'],$needle);
			if($n)$found[$post['id']]=$n;
			$list[$post['id']]=$post;
		}
	}
	
	if(@$found){
		echo '<h3>'.$_l['ext_search']['in blog'].'</h2>';
		arsort($found);
		foreach($found as $id=>$width){
			$post=$list[$id];
			if(gbuffer($post['id'],"close"))$moretitle .= $_l['close_title'];
			br($post);
			if(gbuffer($post['id'],"comments")){$_s['comments']=0; $_l['comments']=$_l['freeze'];}
			$post['admenu']=admenu($post['id']);
			$post['text'] = ext_search_hl(preg_replace('#</?cut>#','',preg_replace('#<cut text="([^"]*)">#sU','',$post['text'])),$needle);
			$post['title'] = (@trim($post['title']) ? $post['title'] : $_l['notitle']);
			$_t['ptup'] .= $_l['ext_search']['in this node found'].'<strong style="color:red;">'.$width.'</strong>'.$_l['ext_search']['matches'].'&laquo;<strong style="color:red;">'.$needle.'</strong>&raquo;';
			include $_i['tpl_patch'].'/post.html';
		}
	}
	else echo '<h3>'.$_l['ext_search']['not found in blog'].'</h3>';
	
	# Начинаем поиск по страницам
	unset($found,$list);# Очищаем результаты предыдущего поиска
	if($pgs=dir2array($_s['pages_dir'])){
		foreach ($pgs as $page){
			ob_start();
			include $_s['pages_dir'].'/'.$page;
			$pg=ob_get_contents();
			ob_end_clean();
			$n=ext_search($pg,$needle);
			if($n){
				$found[$page]=$n;
				$list[$page]=$pg;
			}
		}
	}
	if(@$found){
		arsort($found);
		echo '<h3>'.$_l['ext_search']['in pages'].'</h3><dl>';
		foreach($found as $page=>$width){
			echo '<dt><a href="'.generate_link('pg='.$page).'">'.$page.'</a></dt><dd><p>'.$_l['ext_search']['in this page found'].'<strong style="color:red;">'.$width.'</strong>'.$_l['ext_search']['matches'].'&laquo;<strong style="color:red;">'.$needle.'</strong>&raquo;</p><p>'.ext_search_hl($list[$page],$needle).'</p></dd>'; 
			
		}
		echo '</dl>';
	}
	else echo '<h3>'.$_l['ext_search']['not found in pages'].'</h3>';
}
